<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

<style>
    ul.ztree {
        border: 1px solid #ccc;
        background-color: #fff;
        height: 200px;
        overflow-y: scroll;
        overflow-x: auto;
    }
</style>

<!-- Content Header (Page header) -->
<section class="content-header" style="">
    <h1>
         产品管理
        <small>产品管理页面</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> 主页</a></li>
        <li><a href="#">产品管理</a></li>
        <li class="active">产品管理</li>
    </ol>
</section>

<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <!-- /.box-header -->
                <div class="box-body">
                    <div id="toolbar">
                        <form class="form-inline" id="searchForm">
                            <div class="form-group">
                                <label for="searchArea">地区</label>
                                <input type="text" class="form-control input-sm" name="area" id="searchArea" placeholder="请输入地区名">
                                <label for="searchTitle">产品名</label>
                                <input type="text" class="form-control input-sm" name="title" id="searchTitle" placeholder="请输入产品名">
                            </div>
                            <div class="btn-group btn-group-sm">
                                <button type="button" class="btn btn-default" onclick="javascript:$('table').bootstrapTable('refresh', {silent: true});">
                                    <i class="glyphicon glyphicon-search"></i>
                                    查询
                                </button>
                                <button type="reset" class="btn btn-default">
                                    <i class="glyphicon glyphicon-trash"></i>
                                    清空
                                </button>
                            </div>
                        </form>
                        <div class="btn-group btn-group-sm">
                            <!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
                            <button shiro:hasPermission="item:create" type="button" id="addBtn" class="btn btn-default"
                                    data-toggle="modal"
                                    data-target="#addModal"><i class="glyphicon glyphicon-plus"></i> 新增
                            </button>
                            <!-- Indicates caution should be taken with this action -->
                            <button shiro:hasPermission="item:update" type="button" id="editBtn" class="btn btn-default"
                                    data-toggle="modal"
                                    data-target="#editModal"
                                    data-action="{type:'editable',form:'#editForm',table:'#table'}"
                                    disabled><i class="glyphicon glyphicon-edit"></i> 修改
                            </button>
                            <!-- Indicates a dangerous or potentially negative action -->
                            <button shiro:hasPermission="item:delete" type="button" id="deleteBtn" class="btn btn-default" data-toggle="modal"
                                    data-target="#deleteModal"
                                    data-action="{type:'delete',form:'#deleteForm',idField:'id',table:'#table'}"
                                    disabled><i class="glyphicon glyphicon-remove"></i> 删除
                            </button>
                        </div>
                    </div>
                    <table id="table"></table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->

        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>
<!-- /.content -->

<!-- add Modal -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="addModalLabel">添加产品</h4>
            </div>
            <div class="modal-body">
                <form id="addForm">
                    <fieldset>
                        <legend>添加产品</legend>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="cityId"><span class="asterisk">*</span>地区:</label>
                                <div class="col-sm-4">
                                    <select class="form-control select2" onchange="selectarea()" id="cityId" name="cityId">
                                        <option th:each="area : ${areaList}" th:value="${area.id}" th:text="${area.name}">地区不存在</option>
                                    </select>
                                    <input type="hidden" id="cityName" name="cityName">
                                </div>
                            <label class="col-sm-2 control-label" for="countryId"><span class="asterisk">*</span>县市:</label>
                            <div class="col-sm-4">
                                <select class="form-control select2" id="countryId" name="countryId" onchange="selectCountry(this)">
                                    <option value="">选择县市</option>
                                </select>
                                <input type="hidden" id="countryName" name="countryName">
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="title"><span class="asterisk">*</span>商品名称:</label>
                            <div class="col-sm-4">
                                <input class="form-control" id="title" type="text" name="title" placeholder="输入商品名称"  minlength="2" required/>
                                <div class="help-block with-errors"></div>
                            </div>
                            <label class="col-sm-2 control-label" for="catName"><span class="asterisk">*</span>产品类型</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="catName" name="catName" readonly required>
                                <input type="hidden" id="catId" name="catId">
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>
                      <div class="form-group">
                        <label class="col-sm-2 control-label" for="price"><span class="asterisk">*</span>商品价格:</label>
                        <div class="col-sm-4">
                            <input class="form-control" id="price" type="text" name="price" placeholder="输入商品价格(分)" minlength="1" required/>
                            <div class="help-block with-errors"></div>
                        </div>
                        <label class="col-sm-2 control-label" for="num"><span class="asterisk">*</span>库存数量</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="num" name="num"  required>
                            <div class="help-block with-errors"></div>
                        </div>
                     </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="sellPoint"><span class="asterisk">*</span>产品简介</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" id="sellPoint" name="sellPoint" rows="3" placeholder="产品简介 ..."></textarea>
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>
                    </fieldset>
                    <fieldset>
                        <legend>详细参数</legend>
                        <div class="form-group">
                           <div class="pull-right">
                              <button type="button" class="btn btn-info btn-flat" onclick=saveparamkeys("key")>保存</button>
                               <input type="hidden" id="paramjson" name="paramjson">
                           </div>
                        </div>
                        <div id="addparamgroup">
                            <div class="form-group">
                                <input type="hidden" id="paramId" name="paramId" />
                                <label class="col-sm-2 control-label" for="paramName"><span class="asterisk">*</span>参数名称:</label>
                                <div class="col-sm-4">
                                    <input type="text" class="form-control" id="paramName" name="paramName" readonly required>
                                </div>
                            </div>
                        </div>
                    </fieldset>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="submit" form="addForm" class="btn btn-primary"
                        data-action="{type:'submit',form:'#addForm',url:'@{/item/create}',after:'$.myAction.refreshTable'}">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>

<!-- edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="editModalLabel">修改产品</h4>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <fieldset>
                        <legend>修改产品</legend>
                        <input type="hidden" id="id" name="id"/>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="editcity"><span class="asterisk">*</span>地区:</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="editcity" name="cityName" readonly required>
                                <input type="hidden" id="editcityid" name="city" required>
                                <div class="help-block with-errors"></div>
                            </div>
                            <label class="col-sm-2 control-label" for="editcountryName"><span class="asterisk">*</span>县市:</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="editcountryName" name="countryName" readonly required>
                                <input type="hidden"  id="editcountryId" name="countryId" required>
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="edittitle"><span class="asterisk">*</span>商品名称:</label>
                            <div class="col-sm-4">
                                <input class="form-control" id="edittitle" type="text" name="title" placeholder="输入商品名称"  minlength="2" required/>
                                <div class="help-block with-errors"></div>
                            </div>
                            <label class="col-sm-2 control-label" for="editCatName"><span class="asterisk">*</span>产品类型</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="editCatName" name="catName"  required>
                                <input type="hidden" id="editCatId" name="catId" readonly>
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="editprice"><span class="asterisk">*</span>商品价格:</label>
                            <div class="col-sm-4">
                                <input class="form-control" id="editprice" type="text" name="price" placeholder="输入商品价格(分)" minlength="1" required/>
                                <div class="help-block with-errors"></div>
                            </div>
                            <label class="col-sm-2 control-label" for="editnum"><span class="asterisk">*</span>库存数量</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="editnum" name="num"  required>
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="editsellPoint"><span class="asterisk">*</span>产品简介</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" id="editsellPoint" name="sellPoint" rows="3" placeholder="产品简介 ..." required></textarea>
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>
                    </fieldset>
                    <fieldset>
                        <legend>详细参数</legend>
                        <div class="form-group">
                            <div class="pull-right">
                                <button type="button" class="btn btn-info btn-flat" onclick=saveparamkeys("editkey")>保存</button>
                                <input type="hidden" id="editparamjson" name="paramjson">
                            </div>
                        </div>
                        <div id="editparamgroup">
                            <div class="form-group">
                                <input type="hidden" id="editparamId",name="paramId" />
                                <label class="col-sm-2 control-label" for="paramName"><span class="asterisk">*</span>参数名称:</label>
                                <div class="col-sm-4">
                                    <input type="text" class="form-control" id="editparamName" name="paramName" readonly required>
                                </div>
                            </div>
                        </div>
                    </fieldset>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="submit" form="addForm" class="btn btn-primary"
                        data-action="{type:'submit',form:'#editForm',url:'@{/item/update}',after:'$.myAction.refreshTable'}">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>

<!-- delete modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteSmallModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="deleteSmallModalLabel">删除组</h4>
            </div>
            <div class="modal-body">
                <form id="deleteForm"></form>
                确定要删除选中的 <span class="records"></span> 条记录?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" form="deleteForm" class="btn btn-primary"
                        data-action="{type:'submit',form:'#deleteForm',url:'@{/item/delete}',after:'$.myAction.refreshTable'}">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>


<div id="actionButtons" class="admin-hide">
    <a class="like" href="javascript:void(0)" data-toggle="tooltip" title="Like"><i class="glyphicon glyphicon-heart"></i></a>　
    <a shiro:hasPermission="item:update" class="edit ml10" href="javascript:void(0)" data-toggle="tooltip" title="编辑"><i class="glyphicon glyphicon-edit"></i></a>　
    <a shiro:hasPermission="item:delete" class="remove ml10" href="javascript:void(0)" data-toggle="tooltip" title="删除"><i class="glyphicon glyphicon-remove"></i></a>　
</div>

<!-- zTree -->
<div id="menuContent" class="menuContent" style="display:none;z-index:1989101600;position: absolute;">
    <ul id="tree" class="ztree" style="margin-top:0;"></ul>
</div>

<script th:inline="javascript">

    var $table = $('#table');

    $(function () {
        // bootstrap table初始化
        // http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/
        $table.bootstrapTable({
            url: CONTEXT_PATH + '/item/list',
            idField: 'id',
            columns: [
                {field: 'state', checkbox: true},
                {field: 'id', title: '编号', sortable: true, halign: 'left'},
                {field: 'cityId', title: '地市编号', sortable: true, halign: 'left',visible: false},
                {field: 'cityName',title: '地市名称',sortable: true, halign: 'left'},
                {field: 'countryId',title: '县市编号',sortable: true, halign: 'left',visible: false},
                {field: 'countryName',title: '县市名称',sortable: true, halign: 'left'},
                {field: 'title', title: '商品名称', sortable: true, halign: 'left'},
                {field: 'sellPoint', title: '商品简介', sortable: true, halign: 'left'},
                {field: 'price', title: '价格', sortable: true, halign: 'left'},
                {field: 'num', title: '库存', sortable: true, halign: 'left'},
                {field: 'barcode', title: '条形码', sortable: true, halign: 'left',visible: false},
                {field: 'image', title: '图片', sortable: true, halign: 'left',visible: false  },
                {field: 'catId', title: '产品种类ID', sortable: true, halign: 'left'},
                {field: 'catName', title: '产品种类', sortable: true, halign: 'left'},
                {field: 'up', title: '在架/下架', sortable: true, halign: 'left'},
                {field: 'itemParamValueStr', title: '详细参数', sortable: true, halign: 'left'},
                {
                    field: 'action',
                    title: '操作',
                    halign: 'center',
                    align: 'center',
                    formatter: 'actionFormatter',
                    events: 'actionEvents',
                    clickToSelect: false
                }
            ]
        });
    });




    // 数据表格展开内容
    function detailFormatter(index, row) {
        var html = [];
        $.each(row, function (key, value) {
            html.push('<p><b>' + key + ':</b> ' + value + '</p>');
        });
        //  console.log("html:"+html);
        return html.join('');
    }
    //树的操作节点
    function addBefore(obj) {
        $.fn.zTree.getZTreeObj("tree").destroy();
        $.fn.zTree.init($("#tree"), setting, zNodes);
    }

    function editAfter(obj, row) {
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        treeObj.destroy();
        $.fn.zTree.init($("#tree"), setting, zNodes);
        treeObj.expandAll(true);
    }


    function actionFormatter(value, row, index) {
        //onsole.log("这是个什么鬼！！！"+$('#actionButtons').html());
        return $('#actionButtons').html();
    }

    <!--区域二级联动菜单-->
    function selectarea() {
        // 选中cityId
        var cityId = $("#cityId").val();
        <!--cityName赋值-->
        var cityName=$("#cityId").find("option:selected").text();
        //console.log("选择地市名称："+cityName);
        $("#cityName").val(cityName);

       // console.log("cityid:"+cityId);
        $("#countryId").find("option:not(:first)").remove();
        $.ajax({
            url : "/wximp/area/cityCountry",
            async : false,
            cache : false,
            data : {
                "pid" : cityId
            },
            success : function(data) {
                console.log(data["success"]+","+data["code"]+","+data["msg"]+","+data["data"]);
                var objs = eval(data["data"]);
              //  console.log(objs)
                $("#countryId option").remove();
                var appendstr = '';
                for ( var i =0 ; i<objs.length ; i++ ){
                    if (i == 0){
                        $("#countryName").val(objs[i].name);
                    }
                  //  console.log(objs[i].id+","+objs[i].name);
                    appendstr +=  '<option value="'+objs[i].id+'">'+objs[i].name+'</option>';
                }
               // console.log(appendstr);
                $("#countryId").append(appendstr);
            }
        })
    }
    function selectCountry (choose) {
        var countryName=$(choose).find("option:selected").text();
        console.log("选择县市="+countryName);
        $("#countryName").val(countryName);

    }
    window.actionEvents = {
        'click .like': function (e, value, row, index) {
            alert('You click like icon, row: ' + JSON.stringify(row));
            console.log(value, row, index);
        },
        'click .edit': function (e, value, row, index) {
            $('#editModal').modal('show');
            $('#editForm').fillForm(row);
            //遍历参数组，动态添加参数，要将子列表展开填写值，删除之前的子表属性，重新添加
            // editAfter('', row);
             var objs=JSON.parse(row['paramjson']);
            // console.log("edit参数组："+objs[1].paramId+","+objs[1].paramValue);
            $("#editparamgroup").empty();
            var appendstr = '';
            for ( var i =0 ; i<objs.length ; i++ ){
                appendstr += '<div class="form-group">'
                    +'<label class="col-sm-2 control-label" for="key'+objs[i].paramId+'"><span class="asterisk">*</span>'+objs[i].paramName+':</label>'
                    +'<div class="col-sm-10">'
                    +'<input id="editkey'+objs[i].paramId+'" type="text" class="form-control" name="'+objs[i].paramId+'^'+objs[i].paramName+'" placeholder="输入产品值"'
                    +'minlength="2" value="'+objs[i].paramValue+'" >'
                    +'<div class="help-block with-errors"></div>'
                    + '</div>'
                    +  '</div>'
            }
            // console.log(appendstr);
            $("#editparamgroup").append(appendstr);

            console.log(JSON.stringify(row));
        },
        'click .remove': function (e, value, row, index) {
            $('#deleteModal').modal('show');
            $('.records').html('1');
            var html = '';
            for (var key in row) {
                html += '<input type="hidden" name="' + key + '" value="' + row[key] + '">';
            }
            $('#deleteForm').html(html);
        }
    };

    var setting = {
        check: {
            enable: true,
            chkboxType: {"Y": "", "N": ""},
            chkStyle: "radio",
            radioType: "all"
        },
        view: {
            dblClickExpand: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onCheck: onCheck
        }
    };
    <!--传递过来的list的treee-->
    var itemCatList = [[${itemCatList}]];
    var zNodes = [];
    for (var i in itemCatList) {
        zNodes.push({id: itemCatList[i].id, pId: itemCatList[i].parentId, name: itemCatList[i].name,leaf:itemCatList[i].leaf});
    }

    function onCheck(e, treeId, treeNode) {
        console.log("e="+e+",treeId="+treeId+",treeNode="+treeNode);
        var zTree = $.fn.zTree.getZTreeObj("tree"),
            nodes = zTree.getCheckedNodes(true),
            id = "",
            name = "",
            leaf = "";
        nodes.sort(function compare(a, b) {
            return a.id - b.id;
        });
        <!--复选框还是单选-->
        for (var i = 0, l = nodes.length; i < l; i++) {
            id += nodes[i].id + ",";
            name += nodes[i].name + ",";
            leaf += nodes[i].leaf+","
        }
        <!--去掉末尾的"，"-->
        if (id.length > 0) id = id.substring(0, id.length - 1);
        if (name.length > 0) name = name.substring(0, name.length - 1);
        if (leaf.length > 0) leaf = leaf.substring(0,leaf.length - 1);
        <!--true时，是根，false 叶子-->
       //是个字符串类型 alert(typeof leaf);
        if (leaf == "true") alert("您选择的:"+name+",是种类目录，请选择子节点");
        <!--赋值catid,是一个1,2,3-->
       // console.log("商品种类Id="+$("#catId").val())
        $("#catId").val(id);
        $("#catName").val(name);
        $("#editCatId").val(id);
        $("#editCatName").val(name);
        console.log("选择好了：id="+id+",name="+name+",leaf="+leaf);
        hideMenu();
       <!--根据选择的产品类型，获取组属性和keys-->
         addgroupandkey(id);
       // $('#addparamModal').modal('show')
        //$('#editForm').fillForm(row);

    }

    function addgroupandkey(catId){
        $.ajax({
            url : "/wximp/itemcat/paramkeys",
            async : false,
            cache : false,
            data : {
                "id" : catId
            },
            success : function(data) {
                console.log(data["success"]+","+data["code"]+","+data["msg"]+","+data["data"]);
                <!--解析data中的data数据-->
                var objs = eval(data["data"]);
                $("#addparamgroup").empty();
                var appendstr = '';
                for ( var i =0 ; i<objs.length ; i++ ){
                    appendstr += '<div class="form-group">'
                        +'<label class="col-sm-2 control-label" for="key'+objs[i].id+'"><span class="asterisk">*</span>'+objs[i].paramName+':</label>'
                        +'<div class="col-sm-10">'
                        +'<input id="key'+objs[i].id+'" type="text" class="form-control" name="'+objs[i].id+'^'+objs[i].paramName+'" placeholder="输入产品值"'
                        +'minlength="2">'
                        +'<div class="help-block with-errors"></div>'
                        + '</div>'
                        +  '<div class="help-block with-errors"></div>'
                        +  '</div>'
                }

               // console.log(appendstr);
                $("#addparamgroup").append(appendstr);
            }
        });
    }

    //提交表单
    function saveparamkeys(keyword) {
        //有效性验证
        /*if(!$('#itemAddForm').form('validate')){
            $.messager.alert('提示','表单还未填写完成!');
            return ;
        }*/
        //alert("保存参数：方法,"+keyword);
        //取商品的规格
        var paramJson = [];
        $.each($("input[id^='"+keyword+"']"),function(i,val){
               var idAndName = val.name.split("^",2);
            paramJson.push({
                "paramId":idAndName[0],
                "paramName": idAndName[1],
                "paramValue":val.value
            })
            console.log("i="+i+",id="+idAndName[0]+",name="+idAndName[1]+",value="+val.value);
        });
        paramJson = JSON.stringify(paramJson);
        console.log("json="+paramJson);
        $('#paramjson').attr("value",paramJson);
        $('#editparamjson').attr("value",paramJson);
    };


    <!--显示菜单tree？-->
    function showMenu() {
        //在这里生成Ztree
        $.fn.zTree.init($("#tree"), setting, zNodes);

        var treeObj = $.fn.zTree.getZTreeObj("tree");
        <!--tree显示的位置-->
        var cityObj = $("#catName");
        var cityOffset = $("#catName").offset();
        $("#menuContent").css({left: cityOffset.left + "px", top: cityOffset.top + cityObj.outerHeight()}).slideDown("fast");

        $("body").bind("mousedown", onBodyDown);
    }
<!--显示编辑的菜单-->
    function showMenuOfEdit() {
        $.fn.zTree.init($("#tree"), setting, zNodes);
        var resourceIds = $('#editCatId').val();
        var resourceIdList = resourceIds.split(',');
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        alert("进入编辑菜单功能"+treeObj);
        for (var i in resourceIdList) {
            var id = resourceIdList[i];
            var node = treeObj.getNodeByParam("id", id, null);
            if (node === null) continue;
            treeObj.checkNode(node, true, true);
        }
        var cityObj = $("#editCatName");
        var cityOffset = $("#editCatName").offset();
        $("#menuContent").css({left: cityOffset.left + "px", top: cityOffset.top + cityObj.outerHeight()}).slideDown("fast");

        $("body").bind("mousedown", onBodyDown);
    }

    function hideMenu() {
        $("#menuContent").fadeOut("fast");
        $("body").unbind("mousedown", onBodyDown);
    }

    function onBodyDown(event) {
        if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length > 0)) {
            hideMenu();
        }
    }

   // $.fn.zTree.init($("#tree"), setting, zNodes);
    <!--这里调用ztree-->
    $("#catName").click(showMenu);
    $("#editCatName").click(showMenuOfEdit);


</script>

</html>